package com.gobrs.async.core.timer;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The type Scheduled executor.
 *
 * @program: gobrs -async
 * @ClassName ScheduledExecutor
 * @description:
 * @author: sizegang
 * @create: 2023 -02-27
 */
public class ScheduledExecutor {

    private Integer timerCorePoolSize;

    /**
     * Gets timer core pool size.
     *
     * @return the timer core pool size
     */
    public Integer getTimerCorePoolSize() {
        return timerCorePoolSize;
    }


    /**
     * Instantiates a new Scheduled executor.
     *
     * @param timerCorePoolSize the timer core pool size
     */
    public ScheduledExecutor(Integer timerCorePoolSize) {
        this.timerCorePoolSize = timerCorePoolSize;
    }

    /**
     * Sets timer core pool size.
     *
     * @param timerCorePoolSize the timer core pool size
     */
    public void setTimerCorePoolSize(Integer timerCorePoolSize) {
        this.timerCorePoolSize = timerCorePoolSize;
    }

    /**
     * The Executor.
     */
    volatile ScheduledThreadPoolExecutor executor;

    private volatile boolean initialized;

    /**
     * We want this only done once when created in compareAndSet so use an initialize method
     */
    public void initialize() {

        ThreadFactory threadFactory = new ThreadFactory() {
            final AtomicInteger counter = new AtomicInteger();

            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r, "GobrsTimer-" + counter.incrementAndGet());
                thread.setDaemon(true);
                return thread;
            }

        };
        executor = new ScheduledThreadPoolExecutor(timerCorePoolSize, threadFactory);
        initialized = true;
    }

    /**
     * Gets thread pool.
     *
     * @return the thread pool
     */
    public ScheduledThreadPoolExecutor getThreadPool() {
        return executor;
    }

    /**
     * Is initialized boolean.
     *
     * @return the boolean
     */
    public boolean isInitialized() {
        return initialized;
    }

}
